import axios from 'axios';
import { message } from 'ant-design-vue';
import { getCache, setCache, removeCache } from '@/utils/session';
import qs from 'qs';
import store from '@/store';

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 50000 // 请求超时时间
});

//请求
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = store.getters.token;
  }
  return config;
});

//响应
service.interceptors.response.use(response => {
  const data = response.data;
  console.log('响应数据',data);
  console.log('响应头', response.headers);
  console.log('响应头authorization:', response.headers['authorization']);
  if (response.headers['authorization']) {
    console.log('newToken');
    setCache('TOKEN', response.headers['authorization']);
    //store.setters.token = response.headers['authorization'];
  }
  if (response.headers['content-type'] === 'application/json') {
    if (data.resultCode === 200) {
      console.log('请求成功', response.data);
      return Promise.resolve(response);
    } else {
      console.log('请求失败', response);
      return Promise.reject(response);
    }
  } else {
    console.log('请求成功2', response.data);
    return Promise.resolve(response);
  }
});

let http = {};

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

http.get = function(url, params) {
  return new Promise((resolve, reject) => {
    service
      .get(url, { params })
      .then(res => {
        resolve(res.data);
      })
      .catch(e => {
        reject(e.data);
      });
  });
};

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

http.post = function(url, params) {
  return new Promise((resolve, reject) => {
    service
      .post(url, qs.stringify(params))
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        console.log('请求失败post',err.response);
        reject(err.response.data);
      });
  });
};

http.postJSON = function(url, params) {
  return new Promise((resolve, reject) => {
    service
      .post(url, params)
      .then(res => {
        resolve(res.data);
      })
      .catch(e => {
        reject(e.data);
      });
  });
};

http.postBlob = function(url, params) {
  return new Promise((resolve, reject) => {
    service({
      method: 'post',
      url: url,
      data: params,
      responseType: 'blob'
    })
      .then(res => {
        resolve(res.data);
      })
      .catch(e => {
        reject(e.data);
      });
  });
};
http.getBlob = function(url, params) {
  return new Promise((resolve, reject) => {
    service({
      method: 'get',
      url: url,
      data: params,
      responseType: 'blob'
    })
      .then(res => {
        resolve(res.data);
      })
      .catch(e => {
        reject(e.data);
      });
  });
};

export default http;
